package com.ssm.config;

import com.ssm.utils.DateFormatter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.time.Instant;

/**
 * 功能描述:
 *
 * @author lixiaomeng
 * @date 2018/11/27
 */
public class TimeConverter implements Converter<String, Instant> {

    /**
     * Convert the source object of type {@code S} to target type {@code T}.
     *
     * @param source the source object to convert, which must be an instance of {@code S} (never {@code null})
     * @return the converted object, which must be an instance of {@code T} (potentially {@code null})
     * @throws IllegalArgumentException if the source cannot be converted to the desired target type
     */
    public Instant convert(String source) {
        try {
            if (StringUtils.isNumeric(source)) {
                return Instant.ofEpochMilli(Long.valueOf(source));
            } else {
                return Instant.ofEpochMilli(DateFormatter.parseStrToDate(source).getTime());
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
